//
//  AppDelegate.swift
//  sinaWeiBo
//
//  Created by weixq on 15/7/29.
//  Copyright © 2015年 weixq. All rights reserved.
//

import UIKit

let HMRootViewControllerSwitchNotification = "HMRootViewControllerSwitchNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: HMRootViewControllerSwitchNotification, object: nil)
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        
        window?.rootViewController = defaultViewController()
        
        window?.makeKeyAndVisible()
        
        setupAppearance()
       
        return true
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func switchViewController(n: NSNotification){
        
        let mainVc = n.object as! Bool
        window?.rootViewController =  mainVc ? MainViewController() : WelcomeViewController()
    }
    
    private func defaultViewController() -> UIViewController {
        
        // 判断用户是否登录，没有登录返回主控制器
        if !UserAccount.userLogon {
            return MainViewController()
        }
        // 判断是否需要更新版本，需要更新，需要更新返回新特性，不需要返回欢迎界面
        return  isNewUpdate() ? NewFeatureController() : WelcomeViewController()
    }
    
   private func isNewUpdate() -> Bool{
        // 通过info获取当前版本
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
        
        // 通过偏好设置获取上一个版本
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxzversion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
    
        // 将当前版本号写入到偏好设置
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
        NSUserDefaults.standardUserDefaults().synchronize()
        // 比较当前版本和上一版本
        
        return currentVersion > sandboxzversion
    }
    
    func setupAppearance(){
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        
    }

}

